import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import GitHubProvider from "next-auth/providers/github";
import bcrypt from "bcryptjs";
import type { NextAuthConfig } from "next-auth";
import { DefaultSession } from "next-auth";

// 导入数据库
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/db";

// 为TypeScript扩展Session类型
declare module "next-auth" {
  interface Session {
    user: {
      id: string;
    } & DefaultSession["user"];
  }
}

/**
 * NextAuth.js v5 配置
 */
export const config = {
  // 适配器配置
  adapter: PrismaAdapter(prisma),
  // 会话配置
  session: {
    strategy: "jwt" as const,
    maxAge: 30 * 24 * 60 * 60, // 30天
  },
  // 页面配置
  pages: {
    signIn: "/auth/login",
    signOut: "/auth/logout",
    error: "/auth/error",
  },
  // 提供商配置
  providers: [
    // Google登录
    GoogleProvider({
      clientId: process.env.AUTH_GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || "",
      clientSecret: process.env.AUTH_GOOGLE_SECRET || process.env.GOOGLE_CLIENT_SECRET || "",
      allowDangerousEmailAccountLinking: true,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    }),
    // GitHub登录
    GitHubProvider({
      clientId: process.env.AUTH_GITHUB_ID || process.env.GITHUB_ID || "",
      clientSecret: process.env.AUTH_GITHUB_SECRET || process.env.GITHUB_SECRET || "",
      allowDangerousEmailAccountLinking: true,
    }),
    // 凭据登录
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: { label: "邮箱", type: "email" },
        password: { label: "密码", type: "password" },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          return null;
        }

        try {
          // 查找用户
          const user = await prisma.user.findUnique({
            where: { email: credentials.email as string }
          });

          // 如果用户不存在或没有密码
          if (!user || !user.password) {
            return null;
          }

          // 验证密码
          const isValid = await bcrypt.compare(
            credentials.password as string,
            user.password
          );

          if (!isValid) {
            return null;
          }

          // 返回用户数据
          return {
            id: user.id,
            email: user.email,
            name: user.name,
            image: user.image
          };
        } catch (error) {
          console.error('登录验证错误:', error);
          return null;
        }
      }
    }),
  ],
  callbacks: {
    async session({ session, token }: { session: any; token: any }) {
      if (token && session.user) {
        session.user.id = token.sub || token.id;
      }
      return session;
    },
    async jwt({ token, user }: { token: any; user: any }) {
      if (user) {
        token.id = user.id;
      }
      return token;
    },
    // 重定向回调
    async redirect({ url, baseUrl }) {
      console.log('NextAuth重定向:', { url, baseUrl });
      
      // 处理相对URL (以/开头)
      if (url.startsWith('/')) {
        const fullUrl = `${baseUrl}${url}`;
        console.log('重定向到相对路径:', fullUrl);
        return fullUrl;
      }
      
      // 如果URL已经是绝对路径，检查是否同源
      if (url.startsWith('http')) {
        const urlObj = new URL(url);
        const baseUrlObj = new URL(baseUrl);
        
        // 只有同源URLs才被允许
        if (urlObj.origin === baseUrlObj.origin) {
          console.log('重定向到同源绝对路径:', url);
          return url;
        }
      }
      
      // 默认返回仪表盘
      console.log('默认重定向到仪表盘:', `${baseUrl}/dashboard`);
      return `${baseUrl}/dashboard`;
    }
  },
  // 添加调试以查看详细日志
  debug: true,
  // 添加CSRF保护配置
  secret: process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET || "your-development-secret-do-not-use-in-production",
  // 设置信任主机
  trustHost: true,
  // cookie配置（开发环境不启用secure标志）
  cookies: {
    sessionToken: {
      name: process.env.NODE_ENV === 'production' ? `__Secure-next-auth.session-token` : `next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: process.env.NODE_ENV === 'production' // 仅在生产环境启用secure标志
      }
    }
  },
} satisfies NextAuthConfig;

/**
 * 导出Auth.js v5方法
 */
export const { handlers, auth, signIn, signOut } = NextAuth(config); 